package com.sean.community.comtroller;

import com.sean.community.entity.Event;
import com.sean.community.event.EventProducer;
import com.sean.community.util.CommunityConstant;
import com.sean.community.util.CommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ShareController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);

    private EventProducer eventProducer;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${qiniu.key.access}")
    private String fileCloudServerAccessKey;    // 文件云服务器，用户身份认证密钥

    @Value("${qiniu.key.secret}")
    private String fileCloudServerSecretKey;    // 文件云服务器，文件加密密钥

    @Value("${qiniu.bucket.share.name}")
    private String fileCloudServerBucketName_share;   // 文件云服务器，头像空间名称

    @Value("${qiniu..bucket.share.url}")
    private String fileCloudServerBucketUrl_share;    // 文件云服务器，头像空间 url

    @Autowired
    public void setEventProducer(EventProducer eventProducer) {
        this.eventProducer = eventProducer;
    }

    @RequestMapping(path = "/share", method = RequestMethod.GET)
    @ResponseBody
    public String share(String htmlUrl){
        // 功能 -- 模板对应
        // 生成文件名
        String fileName = CommunityUtil.generateUUID();
        // 使用 Kafka 异步生成图片
        Event event = new Event()
                .setTopic(TOPIC_SHARE)
                .setData("htmlUrl", htmlUrl)
                .setData("fileName", fileName)
                .setData("suffix", ".png");
        eventProducer.fireEvent(event);
        // 返回访问路径
        Map<String, Object> map = new HashMap<>();
//        map.put("shareUrl", domain + contextPath + "/share/image/" + fileName);
        map.put("shareUrl", fileCloudServerBucketUrl_share + "/" + fileName);
        return CommunityUtil.getJSONString(0, null, map);
    }

    // 获取分享图片
    // 解析本地图片，废弃
    @Deprecated
    @RequestMapping(path = "/share/image/{fileName}", method = RequestMethod.GET)
    public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response){
        if(StringUtils.isBlank(fileName)){
            throw new RuntimeException("分享图片文件名为空！");
        }
        response.setContentType("image/png");
        // d:xxx/fileName.png
        File file = new File(wkImageStorage + "/" + fileName + ".png");
        try(
                FileInputStream fileInputStream = new FileInputStream(file); // 编译器会自动添加 finally close 方法
                ServletOutputStream os = response.getOutputStream();
        ){
            // 使用缓冲区一批一批输出
            byte[] buffer = new byte[1024];
            int b = 0;  // 游标
            while((b = fileInputStream.read(buffer)) != -1){
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取分享图片失败：" + e.getMessage());
        }
    }
}
